package algorthm.systemTraning.graph;


import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import java.util.function.Consumer;

/**
 * @className: DFS
 * @Description:
 * @Author: wangyifei
 * @Date: 2024/5/9 8:33
 */
public class DFS {
    public static void iterate(Graph graph , Consumer<Node> action){
        Set<Node> searched = new HashSet<>(graph.nodes.size());
        Stack<Node> stack = new Stack();
        stack.push(graph.nodes.values().iterator().next());
        while(!stack.isEmpty()){
            Node cur = stack.pop() ;
            if(!searched.contains(cur)){
                action.accept(cur);
                searched.add(cur);
            }
            for(int i = 0 ; null != cur.next && i < cur.next.size() ; i++ ){
                if(!searched.contains(cur.next.get(i))){
                    stack.push(cur);
                    stack.push(cur.next.get(i));
                    break ;
                }
            }
        }
    }
}
